import { defineBoot } from '#q-app/wrappers'
import axios from 'axios'

// 环境变量读取，增加调试信息和更强健的回退机制

// 优先级：import.meta.env > process.env > 默认值
// const apiBaseUrl = "https://gem.ccpititc.com"
const apiBaseUrl = "http://192.168.10.62:9002"
console.log(apiBaseUrl,"当前地址")


const api = axios.create({
  baseURL: apiBaseUrl,
  withCredentials: true,  // 添加这行
  headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
  }
})

// 添加响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      // 清除本地存储的认证信息
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      // 跳转到登录页
      window.location.href = '/auth/login'
    }
    return Promise.reject(error)
  }
)

export default defineBoot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  // 输出当前使用的API基础URL，便于调试
  console.log('当前API基础URL:', apiBaseUrl)

  app.config.globalProperties.$axios = axios
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})

export { api }
